package com.wejoy.video.middle.station.api.controller.common;

import com.wejoy.video.middle.station.data.util.IPUtil;
import com.wejoy.video.middle.station.data.vo.RespJSON;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 * @Author miracle_j
 * Create by 2024/9/10 15:04
 */
@RequestMapping("common/ipUtil")
@RestController
public class IpAction {

    // 将 IP 地址转换为 long 类型
    public long ipToLong(InetAddress ip) {
        byte[] octets = ip.getAddress();
        long result = 0;
        for (byte octet : octets) {
            result = result << 8 | (octet & 0xFF);
        }
        return result;
    }

    // 检查 IP 地址是否在指定的网段内
    public boolean isIpInRange(String ip, String subnet, int mask) throws UnknownHostException {
        InetAddress ipAddress = InetAddress.getByName(ip);
        InetAddress subnetAddress = InetAddress.getByName(subnet);

        long ipLong = ipToLong(ipAddress);
        long subnetLong = ipToLong(subnetAddress);

        int shift = 32 - mask;
        long maskLong = (0xFFFFFFFFL << shift) & 0xFFFFFFFFL;

        return (ipLong & maskLong) == (subnetLong & maskLong);
    }

    /**
     * 获取当前请求的 IP 并判断是否在指定网段内
     * @param request HttpServletRequest对象
     * @return RespJSON
     */
    @RequestMapping("/checkIp")
    public RespJSON checkIp(HttpServletRequest request) {
        // 获取请求的 IP 地址
        String ip = IPUtil.getRemoteAddress(request);
        return RespJSON.success(ip);
    }


}
